/*
 * FilePath     : \src\utils\loading.ts
 * Author       : 苏军志
 * Date         : 2023-06-05 09:25
 * LastEditors  : 苏军志
 * LastEditTime : 2024-08-05 11:19
 * Description  : 全局loading效果：合并多次loading请求，避免重复请求
 *                当调用一次showLoading，则次数+1；当次数大于0时，则显示loading
 *                当调用一次hideLoading，则次数-1; 当次数等于0时，则结束loading
 * CodeIterationRecord:
 */
import { ElLoading } from "element-plus";

// 记录页面中存在的loading
let loadingInstance: any;
// 记录当前正在请求的数量
let loadingCount = 0;

const showLoading = (message: string) => {
  if (loadingCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: message || "加载中……",
      background: "rgba(0, 0, 0, 0.7)"
    });
  }
  loadingCount++;
};

const hideLoading = () => {
  loadingCount--;
  if (loadingInstance && loadingCount === 0) {
    loadingInstance.close();
    loadingInstance = null;
  }
};

export { showLoading, hideLoading };
